<template>
  <div class="book-detail-container">
    <div class="book-detail-content">
      <div class="back-button">
        <el-button @click="goBack" type="primary" plain>返回</el-button>
      </div>
      
      <div class="book-detail-card" v-if="book">
        <div class="book-header">
          <div class="book-cover">
            <img :src="book.image || defaultCover" :alt="book.title" @error="handleImageError">
          </div>
          <div class="book-basic-info">
            <h1 class="book-title">{{ book.title }}</h1>
            <p class="book-author">作者：{{ book.author || '未知作者' }}</p>
            <p class="book-publisher">出版社：{{ book.publisher || '未知出版社' }}</p>
            <p class="book-category">分类：{{ book.category || '未分类' }}</p>
            <!-- 隐藏ISBN信息 -->
            <p class="book-price">价格：¥{{ Math.floor(book.price || 0) }}</p>
            <div class="book-actions">
              <el-button 
                type="primary" 
                @click="toggleFavorite"
                :loading="favoriteLoading"
              >
                {{ isFavorite ? '已收藏' : '收藏到书架' }}
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="book-description">
          <h2>书籍简介</h2>
          <p>{{ book.description || '暂无简介' }}</p>
        </div>
      </div>
      
      <div class="loading-container" v-else-if="loading">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div class="error-container" v-else>
        <el-alert
          title="书籍信息加载失败"
          type="error"
          description="无法获取书籍详细信息，请稍后重试"
          show-icon
        />
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'BookDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const book = ref(null)
    const loading = ref(true)
    const favoriteLoading = ref(false)
    const favoriteBooks = ref([])
    const defaultCover = new URL('@/assets/default-cover.jpg', import.meta.url).href
    
    // 检查是否已收藏
    const isFavorite = computed(() => {
      if (!book.value) return false
      return favoriteBooks.value.includes(book.value.id)
    })
    
    // 获取本地存储的收藏书籍
    const getFavoriteBooks = () => {
      const favorites = localStorage.getItem('favoriteBooks')
      if (favorites) {
        try {
          favoriteBooks.value = JSON.parse(favorites)
        } catch (e) {
          favoriteBooks.value = []
        }
      } else {
        favoriteBooks.value = []
      }
    }
    
    // 保存收藏书籍到本地存储
    const saveFavoriteBooks = () => {
      localStorage.setItem('favoriteBooks', JSON.stringify(favoriteBooks.value))
    }
    
    // 切换收藏状态
    const toggleFavorite = () => {
      if (!book.value) return
      
      favoriteLoading.value = true
      
      // 模拟API调用延迟
      setTimeout(() => {
        try {
          if (isFavorite.value) {
            // 取消收藏
            favoriteBooks.value = favoriteBooks.value.filter(id => id !== book.value.id)
            ElMessage.success('已取消收藏')
          } else {
            // 添加收藏
            favoriteBooks.value.push(book.value.id)
            ElMessage.success('已添加到书架')
          }
          
          // 保存到本地存储
          saveFavoriteBooks()
        } catch (error) {
          ElMessage.error('操作失败，请重试')
          console.error('收藏操作失败:', error)
        } finally {
          favoriteLoading.value = false
        }
      }, 300)
    }
    
    const fetchBookDetail = async (id) => {
      try {
        loading.value = true
        const response = await fetch(`/api/fanqie/${id}`)
        const result = await response.json()
        
        if (result.success && result.data) {
          book.value = result.data
        } else {
          console.error('获取书籍详情失败:', result.message)
        }
      } catch (error) {
        console.error('获取书籍详情时发生错误:', error)
      } finally {
        loading.value = false
      }
    }
    
    const goBack = () => {
      router.go(-1)
    }
    
    const handleImageError = (event) => {
      event.target.src = defaultCover
    }
    
    onMounted(() => {
      const bookId = route.params.id
      if (bookId) {
        // 获取收藏书籍列表
        getFavoriteBooks()
        fetchBookDetail(bookId)
      } else {
        loading.value = false
      }
    })
    
    return {
      book,
      loading,
      favoriteLoading,
      isFavorite,
      defaultCover,
      goBack,
      handleImageError,
      toggleFavorite
    }
  }
})
</script>

<style scoped>
.book-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.book-detail-content {
  max-width: 1200px;
  margin: 0 auto;
}

.back-button {
  margin-bottom: 20px;
}

.book-detail-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.book-header {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  margin-bottom: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #eee;
}

.book-cover {
  flex: 0 0 200px;
}

.book-cover img {
  width: 100%;
  height: auto;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.book-basic-info {
  flex: 1;
}

.book-title {
  font-size: 28px;
  color: #333;
  margin: 0 0 15px 0;
}

.book-author,
.book-publisher,
.book-category,
.book-isbn,
.book-price {
  font-size: 16px;
  color: #666;
  margin: 8px 0;
}

.book-description h2 {
  font-size: 22px;
  color: #333;
  margin: 0 0 15px 0;
}

.book-description p {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
}

.loading-container,
.error-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 30px;
}

@media (max-width: 768px) {
  .book-detail-container {
    padding: 10px;
  }
  
  .book-header {
    flex-direction: column;
  }
  
  .book-cover {
    flex: 0 0 auto;
    text-align: center;
  }
  
  .book-title {
    font-size: 24px;
  }
}
</style>